<template>
  <div class="prescriptions-container">
    <van-nav-bar
      title="药方信息"
      left-arrow
      @click-left="router.back()"
    />

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell-group v-for="prescription in prescriptions" :key="prescription.id" inset class="my-2">
          <van-cell 
            :title="`处方编号：${prescription.prescriptionNo}`" 
            :label="`开具时间：${formatDateTime(prescription.createTime)}`"
          >
            <template #value>
              <van-tag :type="getStatusType(prescription.status)">
                {{ getStatusText(prescription.status) }}
              </van-tag>
            </template>
          </van-cell>
          <van-cell title="开具医生" :value="prescription.doctorName" />
          <van-cell title="就诊科室" :value="prescription.departmentName" />
          
          <!-- 药品列表 -->
          <div class="medicine-list p-4">
            <div class="text-sm text-gray-500 mb-2">药品清单：</div>
            <van-cell-group inset>
              <van-cell v-for="medicine in prescription.medicines" :key="medicine.id">
                <template #title>
                  <div class="medicine-item">
                    <span class="medicine-name">{{ medicine.name }}</span>
                    <div class="medicine-info text-sm text-gray-500">
                      <span>{{ medicine.specification }}</span>
                      <span>用法：{{ medicine.usage }}</span>
                      <span>用量：{{ medicine.dosage }}</span>
                      <span>频次：{{ medicine.frequency }}</span>
                    </div>
                  </div>
                </template>
                <template #value>
                  <div class="text-right">
                    <div>{{ medicine.quantity }}{{ medicine.unit }}</div>
                    <div class="text-sm text-gray-500">￥{{ medicine.price }}</div>
                  </div>
                </template>
              </van-cell>
            </van-cell-group>
          </div>

          <!-- 费用信息 -->
          <van-cell title="处方总额" :value="`￥${prescription.totalAmount}`" />
          <van-cell title="医保报销" :value="`￥${prescription.insuranceAmount}`" v-if="prescription.insuranceAmount > 0" />
          <van-cell title="实付金额" :value="`￥${prescription.actualAmount}`" />

          <!-- 操作按钮 -->
          <van-cell v-if="prescription.status === 0">
            <template #title>
              <van-button 
                type="primary" 
                size="small" 
                block
                @click="handlePay(prescription)"
                :loading="payLoading === prescription.id"
              >
                去支付
              </van-button>
            </template>
          </van-cell>
        </van-cell-group>
      </van-list>
    </van-pull-refresh>

    <!-- 无记录提示 -->
    <div v-if="!loading && prescriptions.length === 0" class="empty-tip">
      <van-empty description="暂无处方记录" />
    </div>

    <!-- 支付弹窗 -->
    <van-action-sheet v-model="showPaySheet" title="选择支付方式">
      <div class="pay-methods p-4">
        <van-cell-group inset>
          <van-cell 
            v-for="method in payMethods" 
            :key="method.id"
            :title="method.name"
            clickable
            @click="confirmPay(method.id)"
          >
            <template #icon>
              <van-icon :name="method.icon" class="mr-2" />
            </template>
          </van-cell>
        </van-cell-group>
      </div>
    </van-action-sheet>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { getPrescriptions } from '../api'

const router = useRouter()
const prescriptions = ref([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const currentPage = ref(1)
const pageSize = 10
const payLoading = ref(null)
const showPaySheet = ref(false)
const currentPrescription = ref(null)

// 支付方式列表
const payMethods = [
  { id: 1, name: '微信支付', icon: 'wechat-pay' },
  { id: 2, name: '支付宝支付', icon: 'alipay' },
  { id: 3, name: '医保卡支付', icon: 'card' }
]

const loadPrescriptions = async () => {
  try {
    const res = await getPrescriptions({
      page: currentPage.value,
      size: pageSize
    })
    
    if (refreshing.value) {
      prescriptions.value = []
      refreshing.value = false
    }
    
    prescriptions.value.push(...res.content)
    loading.value = false
    
    if (res.content.length < pageSize) {
      finished.value = true
    } else {
      currentPage.value += 1
    }
  } catch (error) {
    console.error('获取处方列表失败：', error)
    showToast('获取处方列表失败')
    loading.value = false
  }
}

const onLoad = () => {
  loadPrescriptions()
}

const onRefresh = () => {
  finished.value = false
  currentPage.value = 1
  loadPrescriptions()
}

const handlePay = (prescription) => {
  currentPrescription.value = prescription
  showPaySheet.value = true
}

const confirmPay = async (payMethodId) => {
  try {
    showPaySheet.value = false
    payLoading.value = currentPrescription.value.id
    
    // TODO: 调用支付接口
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    showToast('支付成功')
    
    // 刷新列表
    finished.value = false
    currentPage.value = 1
    prescriptions.value = []
    loadPrescriptions()
  } catch (error) {
    console.error('支付失败：', error)
    showToast('支付失败')
  } finally {
    payLoading.value = null
    currentPrescription.value = null
  }
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

const getStatusType = (status) => {
  const types = {
    0: 'warning',   // 待支付
    1: 'success',   // 已支付
    2: 'primary',   // 已配药
    3: 'success'    // 已完成
  }
  return types[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    0: '待支付',
    1: '已支付',
    2: '配药中',
    3: '已完成'
  }
  return texts[status] || '未知'
}

onMounted(() => {
  loadPrescriptions()
})
</script>

<style scoped>
.prescriptions-container {
  min-height: 100vh;
  background-color: var(--background-color);
  padding-bottom: 20px;
}

.medicine-list {
  background-color: #fff;
}

.medicine-item {
  display: flex;
  flex-direction: column;
}

.medicine-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.medicine-info {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.empty-tip {
  padding: 40px 0;
}

.pay-methods {
  padding-bottom: env(safe-area-inset-bottom);
}
</style> 